package com.poisonh.unifiedauth.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;

import com.bumptech.glide.Glide;
import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.dao.UserinfoDaoImpl;
import com.poisonh.unifiedauth.model.BusinessCard;
import com.poisonh.unifiedauth.model.IdCard;
import com.poisonh.unifiedauth.model.UserInfoModel;
import com.poisonh.unifiedauth.ui.svprogresshud.SVProgressHUD;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.ImageUtils;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.PreferencesUtils;
import com.poisonh.unifiedauth.utils.RegexUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;
import com.poisonh.unifiedauth.widget.CircleImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import io.realm.Realm;

/**
 * 设置用户头像
 * Created by PoisonH on 2016/6/27.
 */
public class SettingCardActivity extends BaseActivity implements View.OnClickListener {
    private CircleImageView mMyHead;

    private BusinessCard mBusinessCard;
    // private String filePath;

    /* 头像文件 */
    private static final String IMAGE_FILE_NAME = "/head.png";

    /* 请求识别码 */
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    public static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;

    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private int output_X = 160;
    private int output_Y = 160;
    private String imagePath = "null";
    private String mStrPhone = "null";
    private String compareImg = "null";

    private File head;
    private DrawableEditText mName;
    private DrawableEditText mMoble;
    private DrawableEditText mTel;
    private DrawableEditText mEMail;
    private DrawableEditText mCompany;
    private Button later;

    @Override
    protected void loadContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_settingcard);
        mStrPhone = getIntent().getStringExtra("PHONE");
      //  File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/head.png");
                 //  imagePath=file.getAbsolutePath();

        imagePath = ImageUtils.getScaleSavePath(this);
       // head= (File) getIntent().getSerializableExtra("head");//获取文件
        initTitleView();
        initView();
        loadModel();
        if (mBusinessCard != null) {
            showViewData();
        } else {
            //从SharedPreferences获取数据:
//            SharedPreferences preferences = getSharedPreferences("user_state", Context.MODE_PRIVATE);
//            Boolean user_head_state = preferences.getBoolean("user_head_state", false);
            mMoble.setText(mStrPhone);
            Realm realm = Realm.getDefaultInstance();
            IdCard mIdCard = realm.where(IdCard.class).equalTo("uid", mStrUserId).findFirst();
            realm.close();

            if(mIdCard!=null){

            if (mIdCard.getCert() == 1) {
                compareImg=mIdCard.getCompareImg();//得到的认证头像图片
                if(compareImg!=null){

                    //是这样的  我第一次注册的图片
                Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL+compareImg)
                        .into(mMyHead);
                }
            } else {
                Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL + ConstantUitls.DEFAULTHEADIMG).into(mMyHead);
            }
            }

        }


    }

    @Override
    protected void initView() {
        setTitleTxt("设置名片");
        mRightBtn.setVisibility(View.GONE);
        mLeftBtn.setOnClickListener(this);
        mLeftBtn.setVisibility(View.INVISIBLE);
        mMyHead = (CircleImageView) findViewById(R.id.setting_my_head);
        mTvRight.setVisibility(View.VISIBLE);
        mTvRight.setText("保存");
        mTvRight.setOnClickListener(this);
        mMyHead.setOnClickListener(this);

        mName = (DrawableEditText) findViewById(R.id.det_name);
        mMoble = (DrawableEditText) findViewById(R.id.det_mobile);
        mTel = (DrawableEditText) findViewById(R.id.det_tel);
        mEMail = (DrawableEditText) findViewById(R.id.det_mail);
        mCompany = (DrawableEditText) findViewById(R.id.det_company);
        later= (Button) findViewById(R.id.later);//以后再说
        later.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_right_txt://保存

                if (validateData()) {

                    upUserHead();
                }


                break;
            case R.id.setting_my_head:
               // ShotPhoto();
                break;
        }
    }



    /**
     * 拍照
     */
//    private void ShotPhoto() {
//       Intent mShotPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//       mShotPhoto.putExtra("android.intent.extras.CAMERA_FACING", 1);

//        Intent mShotPhoto = new Intent(this, CameraActivity.class);
//
//        mShotPhoto.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));

//        startActivityForResult(mShotPhoto, CODE_CAMERA_REQUEST);
//    }

    /**
     * 裁剪原始的图片
     */
//    public void cropRawPhoto(Uri uri) {
//
//        Intent intent = new Intent("com.android.camera.action.CROP");//代码会跳转到Android系统自带的一个图片剪裁页面，点击确定之后就会得到一张图片.
//        //   Intent intent = new Intent();
//        intent.setDataAndType(uri, "image/*");
//
//
//        // 设置裁剪
//        intent.putExtra("crop", "true");
//
//        // aspectX , aspectY :宽高的比例
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//
//        // outputX , outputY : 裁剪图片宽高
//        intent.putExtra("outputX", output_X);
//        intent.putExtra("outputY", output_Y);
//        intent.putExtra("return-data", true);
//        startActivityForResult(intent, CODE_RESULT_REQUEST);
//    }


    /**
     * 提取保存裁剪之后的图片数据，并设置头像部分的View
     */
//    private void setImageToHeadView(Intent intent) {
//        Bundle extras = intent.getExtras();
//        if (extras != null) {
//            Bitmap photo = extras.getParcelable("data");
//            //uploadPic(photo);
//          //  imagePath = Photoutils.savePhoto(photo, Environment.getExternalStorageDirectory().getAbsolutePath(), "/head");
//            mMyHead.setImageBitmap(photo);
//        }
//    }




    /**
     * 检查设备是否存在SDCard的工具方法
     */
//    public static boolean hasSdcard() {
//        String state = Environment.getExternalStorageState();
//        return state.equals(Environment.MEDIA_MOUNTED);
//    }

//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
//
//        super.onActivityResult(requestCode, resultCode, intent);
//        // 用户没有进行有效的设置操作，返回
//        if (resultCode == RESULT_CANCELED) {
//            //  Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
//            return;
//        }
//
//        switch (requestCode) {
//            case CODE_GALLERY_REQUEST:
//                cropRawPhoto(intent.getData());
//                break;
//
//            case CODE_CAMERA_REQUEST:// 相机捕获到图片返回的code 图片
//                if (hasSdcard()) {
//                    File tempFile = new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME);
//                    //  cropRawPhoto(Uri.fromFile(tempFile));//原来要用的工具类
//
//                    String filePath = ImageUtils.scaleSaveBitmap(this, tempFile.getAbsolutePath());
//                   // setImageToHeadView(filePath);
//                   //  UploadPicture(imagePath);//请求人脸识别的方法
//
//
//                } else {
//                    Toast.makeText(getApplication(), "没有SDCard!", Toast.LENGTH_LONG).show();
//                }
//
//                break;
//
//            case CODE_RESULT_REQUEST:
//                if (intent != null) {
//                    setImageToHeadView(intent);
//                }
//                break;
//        }
//
//
//    }


    /**
     * 更新用户头像
     */
    private void upUserHead() {
        SVProgressHUD.showWithStatus(this, "加载中...");
        HttpParams params = new HttpParams();
        if (mBusinessCard != null) {
            params.put("id", mBusinessCard.getId());
        }
        if (!imagePath.equals("null")) {  //只有修改头像数据才上传
            File tempFile = new File(imagePath);
            params.put("headImgFile", tempFile);
        }

        params.put("userId", mStrUserId);
        params.put("token", mStrUserToken);


        params.put("name", mName.getText());
        params.put("mobile", mMoble.getText());
        params.put("tel", mTel.getText());
        params.put("email", mEMail.getText());
        params.put("company", mCompany.getText());


        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.SAVEBUSINESS, params, new MyHttpsUtils.ResultCallback() {
            @Override
            public void onSuccess(String response) {
                JSONObject resultsJson = null;
                Realm realm = null;
                try {
                    JSONObject responseJson = new JSONObject(response);
                    resultsJson = responseJson.getJSONObject("results");
                    realm = Realm.getDefaultInstance();
                    realm.beginTransaction();
                    BusinessCard b = realm.createOrUpdateObjectFromJson(BusinessCard.class, resultsJson);//保存成功。
                    realm.commitTransaction();

                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    if (realm != null) {
                        realm.close();
                    }
                }

                ToastUtils.showToast(SettingCardActivity.this, "保存成功");
                SVProgressHUD.dismiss(SettingCardActivity.this);


             //   sendChangeHeadBR(response);

//                Intent mIntent = new Intent(SettingCardActivity.this, MainActivity.class);
//                mIntent.putExtra("PHONE", mStrPhone);
//                startActivity(mIntent);


                //只有从身份管理页面进入名片修改时有用
                Intent mIntent = new Intent();
                mIntent.putExtra("result", "seccuss");
                setResult(IdentityCardActivity.TYPE_IDCARD, mIntent);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                finish();
            }

            @Override
            public void onFailure(String failReason) {

                ToastUtils.showToast(SettingCardActivity.this, failReason);

                SVProgressHUD.dismiss(SettingCardActivity.this);
            }
        });
    }

    /**
     * 发送更改头像的广播
     */
    private void sendChangeHeadBR(String response) {
        //根据id查询用户
        UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(this);
        try {
            UserInfoModel model = mUserinfoDaoImpl.queryReturnOne(mStrUserId);
            JSONObject object = new JSONObject(response);
            JSONObject data = object.getJSONObject("results");
            model.setmStrHeadUrl(ConstantUitls.REQUEDT_IMG_URL + data.getString("headImgUrl"));
            mUserinfoDaoImpl.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Intent mInent = new Intent("HEAD_CHANGE");
        this.sendBroadcast(mInent);
    }


    private void loadModel() {
        String mUserId = PreferencesUtils.getString(this, "ID");
        Realm realm = Realm.getDefaultInstance();
        BusinessCard model = realm.where(BusinessCard.class).equalTo("uid", mUserId).findFirst();
        realm.close();
        if (model != null) {
            mBusinessCard = model;
        }
    }

    /**
     * 加载并显示数据
     */
    private void showViewData() {

        if (mBusinessCard != null) {

            mName.setText(mBusinessCard.getName());
            mMoble.setText(mBusinessCard.getMobile());
            mTel.setText(mBusinessCard.getTel());
            mEMail.setText(mBusinessCard.getEmail());
            mCompany.setText(mBusinessCard.getCompany());
            Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL + mBusinessCard.getHeadImg()).into(mMyHead);
        }
    }


    //验证数据
    private boolean validateData() {
        if (mBusinessCard == null && imagePath.equals("null")) { //只有添加时验证头像，修改时不验证
            ToastUtils.showToast(SettingCardActivity.this, "头像未设置！");
            return false;
        }
        String strName = mName.getText();
        if (strName == null || "".equals(strName.trim())) {
            ToastUtils.showToast(this, "请输入姓名");
            return false;
        }

        String strMoble = mMoble.getText();
        if (strMoble == null || "".equals(strMoble.trim())) {
            ToastUtils.showToast(this, "请输入手机号");
            return false;
        }
        if (!RegexUtils.isMobilePhoneNumber(strMoble)) {
            ToastUtils.showToast(this, "请输入正确的手机号");
            return false;
        }

//        String strTel = mTel.getText();
//        if (strTel==null||"".equals(strTel.trim())){
//            ToastUtils.showToast(this, "请输入座机号");
//            return  false;
//        }
//
//        String strEMail = mEMail.getText();
//        if (strEMail==null||"".equals(strEMail.trim())){
//            ToastUtils.showToast(this, "请输入邮箱地址");
//            return  false;
//        }
//        if (!RegexUtils.isEmail(strEMail)){
//            ToastUtils.showToast(this, "请输入正确的邮箱地址");
//            return  false;
//        }
//
//        String strCompany = mCompany.getText();
//        if (strCompany==null||"".equals(strCompany.trim())){
//            ToastUtils.showToast(this, "请输入单位地址");
//            return  false;
//        }

        return true;
    }


}
